package com.kangdi.riggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kangdi.riggie.common.Result;
import com.kangdi.riggie.dto.OrdersDto;
import com.kangdi.riggie.entity.OrderDetail;
import com.kangdi.riggie.entity.Orders;
import com.kangdi.riggie.service.OrderDetailService;
import com.kangdi.riggie.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @PostMapping("submit")
    public Result<String> submit(@RequestBody Orders orders){
        ordersService.addOrder(orders);
        return Result.success("购买成功");
    }
    @GetMapping("userPage")
    public Result<Page<OrdersDto>> userPage(int page, int pageSize){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        ordersService.page(ordersPage);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> list =records.stream().map((item)->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            Long id = item.getId();
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,id);
            List<OrderDetail> detailList = orderDetailService.list(queryWrapper);
            ordersDto.setOrderDetails(detailList);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);
        return Result.success(ordersDtoPage);
    }
}
